import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_permission/yt_tab_view_model.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/tasks/create_repair_task/repair_task_operate_enum.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/task/task_services.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';

import 'list_page_view.dart';

class TaskListController extends GetxController
    with GetTickerProviderStateMixin {
  TaskServices taskServices = Get.find<TaskServices>();

  int curTabIndex = 0;

  BrnSearchTextController searchController = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  FocusNode focusNode = FocusNode();
  String keyWord = '';
  List<YtTabViewModel> get tabs => [
        YtTabViewModel(
          permissionString: PermissionConstant.operationWorkOrderInstall,
          labelString: ResKey.workOrderInstall.tr,
          imageString: '',
          permissionWidget: ListPageView(
            tabIndex: 0,
            key: installKey,
            service: taskServices.getInstallTaskList,
          ),
        ),
        YtTabViewModel(
          permissionString: PermissionConstant.operationWorkOrderMaintenance,
          labelString: ResKey.workOrderMaintenance.tr,
          imageString: '',
          permissionWidget: ListPageView(
            tabIndex: 1,
            key: repairKey,
            service: taskServices.getRepairTaskList,
          ),
        ),
        YtTabViewModel(
          permissionString: PermissionConstant.operationWorkOrderFault,
          labelString: ResKey.workOrderCustomFault.tr,
          imageString: '',
          permissionWidget: ListPageView(
              tabIndex: 2,
              key: reportKey,
              service: taskServices.getReportTaskList),
        ),
      ];

  List<String> get conditions =>
      [ResKey.workOrderInstall.tr, ResKey.workOrderMaintenance.tr];

  GlobalKey<ListPageViewState> installKey = GlobalKey<ListPageViewState>();
  GlobalKey<ListPageViewState> repairKey = GlobalKey<ListPageViewState>();
  GlobalKey<ListPageViewState> reportKey = GlobalKey<ListPageViewState>();

  // 0 :任务模块 1:代办任务
  int from = 0;
  // 标题
  String get title => from == 1 ? ResKey.agencyTasks.tr : ResKey.workOrder.tr;
  @override
  void onInit() {
    super.onInit();
    initData();
  }

  initData() {
    Log.d('TaskListController===onInit111');

    ///initState 中添加监听，记得销毁
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (textController.text.isNotEmpty) {
          searchController.isClearShow = true;
          searchController.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (textController.text.isNotEmpty) {
          searchController.isClearShow = true;
        }
      }
    });
  }

  @override
  void onReady() {}

  updateTaskType(int index) {
    curTabIndex = index;
    update();
  }

  commit(String content) {
    keyWord = content;
    refresh();
  }

  addHandler(BuildContext context) {
    int selectedIndex = -1;
    showDialog(
        context: context,
        builder: (_) => StatefulBuilder(
              builder: (context, state) {
                return BrnSingleSelectDialogWidget(
                    isClose: true,
                    title: ResKey.pleSelectedCreateOrderType.tr,
                    conditions: conditions,
                    checkedItem:
                        selectedIndex == -1 ? null : conditions[selectedIndex],
                    submitText: ResKey.sure.tr,
                    isCustomFollowScroll: true,
                    themeData: BrnDialogConfig(
                        dialogWidth: 300.w,
                        contentTextStyle: BrnTextStyle(fontSize: 16.sp)),
                    onItemClick: (BuildContext context, int index) {
                      selectedIndex = index;
                      state(() {});
                    },
                    onSubmitClick: (data) {
                      if (data == conditions[0]) {
                        toCreateInstall();
                      } else if (data == conditions[1]) {
                        toCreateRepair();
                      }
                    });
              },
            ));
  }

  Map<String, dynamic> setQueryParam() {
    Map<String, dynamic> extraParam = {
      'id': keyWord,
    };
    return extraParam;
  }

  @override
  refresh({RefereshType refereshType = RefereshType.refresh}) {
    switch (curTabIndex) {
      case 0:
        refreshInstall(refereshType: refereshType);
        break;
      case 1:
        refreshRepair(refereshType: refereshType);
        break;
      default:
        refreshReport(refereshType: refereshType);
        break;
    }
  }

  toFilter(BuildContext context) {
    switch (curTabIndex) {
      case 0:
        installKey.currentState?.toFilter(context);
        break;
      case 1:
        repairKey.currentState?.toFilter(context);
        break;
      case 2:
        reportKey.currentState?.toFilter(context);
        break;
      default:
    }
  }

  refreshInstall({RefereshType refereshType = RefereshType.refresh}) {
    installKey.currentState?.extraParam = setQueryParam();
    installKey.currentState?.onRefresh(refereshType: RefereshType.initial);
  }

  refreshRepair({RefereshType refereshType = RefereshType.refresh}) {
    repairKey.currentState?.extraParam = setQueryParam();
    repairKey.currentState?.onRefresh(refereshType: RefereshType.initial);
  }

  refreshReport({RefereshType refereshType = RefereshType.refresh}) {
    reportKey.currentState?.extraParam = setQueryParam();
    reportKey.currentState?.onRefresh(refereshType: RefereshType.initial);
  }

  // 去创建安装单
  toCreateInstall() {
    Get.toNamed(RouterPath.createInstallTask);
  }

  // 去创建维修单
  toCreateRepair() {
    Get.toNamed(RouterPath.createRepairTask,
        arguments: {'type': RepairTaskTypeOperateEnum.create});
  }

  @override
  void onClose() {
    focusNode.dispose();
    textController.dispose();
  }
}
